package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.CompanySummary;
import com.woyao.core.model.GetMyCompanyResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;


public class ConfirmOrgActivity extends AppCompatActivity {

    SearchView mSearchView;
    LinearLayout companies ;

    ProgressDialog progressDialog;

    private Integer MEMBER_CODE = 600;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_org);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        companies = (LinearLayout) findViewById(R.id.id_companies);

        mSearchView = (SearchView) findViewById(R.id.id_search_content);
//        mSearchView.setVisibility(View.GONE);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                searchCompany(newText);
                return false;
            }
        });



            this.setTitle("选择组织");


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("member_id", 0 );
        intent.putExtra("member_title", "");
        setResult(0, intent);
        finish();
        return true;
    }


    private void addOrg( final String org_title) {


        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在创建组织······");
        progressDialog.show();


        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);

                Call<BaseResponse> responseCall = svc.addOrg(userId,  org_title);
                BaseResponse response = null;
                try {
                    response = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null && response.isSuccess()) {
                    Intent intent = new Intent();
                    intent.putExtra("org_id", Integer.parseInt(response.getMessage()));
                    intent.putExtra("org_title",org_title);
                    intent.putExtra("id", 0);
                    intent.setClass(ConfirmOrgActivity.this, MemberActivity.class);
                    startActivityForResult(intent, MEMBER_CODE);


                }
                progressDialog.dismiss();
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);
    }
    private void searchCompany(final String content){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();

        AsyncTask<Void,Void, GetMyCompanyResponse> task =
                new AsyncTask<Void, Void, GetMyCompanyResponse>() {
                    @Override
                    protected GetMyCompanyResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<GetMyCompanyResponse> responseCall = svc.searchOrg(userId,content);
                        try {
                            GetMyCompanyResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final GetMyCompanyResponse response) {
                        progressDialog.dismiss();
                        renderIt(response.getCompanylist());

                    }
                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();
    }

    //    BusinessSelect select;
    private void renderIt( ArrayList<CompanySummary> the_companies ) {

        companies.removeAllViews();

        LinearLayout summary = (LinearLayout) LayoutInflater.from(ConfirmOrgActivity.this).inflate(R.layout.summary_item, null);
        TextView sum =  summary.findViewById(R.id.summary_text);
        sum.setText("组织数：" + the_companies.size());
        companies.addView(summary);
        for (final CompanySummary cs :  the_companies) {
            LinearLayout convertView = (LinearLayout) LayoutInflater.from(ConfirmOrgActivity.this).inflate(R.layout.org_item, null);

            TextView title = (TextView) convertView.findViewById(R.id.org_title);
            TextView desc = (TextView) convertView.findViewById(R.id.org_desc);

            title.setText(cs.getTitle());
            if  (cs.getDescription() == null || cs.getDescription().equals("")){
                desc.setVisibility(View.GONE);
            }

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (cs.getId().equals( "0" )){
                        addOrg( cs.getTitle().replace("(新建)",""));
                    }else {
                        Intent intent = new Intent();
                        intent.putExtra("org_id", cs.getId());
                        intent.putExtra("org_title", cs.getTitle());
                        intent.putExtra("id", 0);
                        intent.setClass(ConfirmOrgActivity.this, MemberActivity.class);
                        startActivityForResult(intent, MEMBER_CODE);
                    }
                }
            });
            companies.addView(convertView);
            LinearLayout split = (LinearLayout) LayoutInflater.from(ConfirmOrgActivity.this).inflate(R.layout.splitter, null);
            companies.addView(split);
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == MEMBER_CODE && resultCode == 666) {
            Intent intent = new Intent();
            String themembertitle = data.getStringExtra("member_title");
            String thememberid = data.getStringExtra("member_id");
            intent.putExtra("member_id", thememberid );
            intent.putExtra("member_title", themembertitle);
            setResult(666, intent);
            finish();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("member_id", 0 );
            intent.putExtra("member_title", "");
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}